<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="年份" prop="year">
              <el-date-picker date-format="YYYY" value-format="YYYY" type="year" v-model="queryParams.year" style="width: 160px" />
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName">
              <el-input :placeholder="queryParams.deptName" clearable style="width: 160px" :disabled="true" />
            </el-form-item>
            <!--            <el-form-item label="预算科目编码" prop="subjectCode" label-width="100">-->
            <!--              <el-input v-model="queryParams.subjectCode" placeholder="请输入预算科目编码" clearable-->
            <!--                        @keyup.enter="handleQuery" style="width: 160px" />-->
            <!--            </el-form-item>-->
            <el-form-item label="预算科目名称" prop="subjectName" label-width="100">
              <el-input
                v-model="queryParams.subjectName"
                placeholder="请输入预算科目名称"
                clearable
                @keyup.enter="handleQuery"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item label="申请主题" prop="applyTheme">
              <el-input v-model="queryParams.applyTheme" placeholder="请输入申请主题" clearable @keyup.enter="handleQuery" style="width: 160px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['fill:apply:add']"> 申请 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['fill:apply:export']"> 导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </el-row>
      </template>
      <el-table border v-loading="loading" :data="applyList" class="enhanced-table">
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <el-table-column label="部门编号" align="center" prop="deptCode" show-overflow-tooltip />
        <el-table-column label="部门名称" align="center" prop="deptName" min-width="120" show-overflow-tooltip />
        <el-table-column label="院区" align="center" prop="yardName" />
        <el-table-column label="申请主题" align="center" prop="applyTheme" min-width="120" show-overflow-tooltip />
        <el-table-column label="预算科目编码" align="center" prop="subjectCode" min-width="120" show-overflow-tooltip />
        <el-table-column label="预算科目名称" align="center" prop="subjectName" min-width="120" show-overflow-tooltip />
        <el-table-column label="申请金额" align="center" prop="applyMoney" min-width="120" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="approval_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170" />
        <el-table-column label="季度" align="center" prop="quarterName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" :width="columnLength">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button type="success" circle link @click="handleView(scope.row)">
                <svg-icon icon-class="View" />
              </el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="scope.row.status === 'draft'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fill:apply:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.status === 'draft'">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fill:apply:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看附件" placement="top" v-if="scope.row.ossId != null">
              <el-button type="success" circle link @click="handleViewFile(scope.row)">
                <svg-icon icon-class="excel2" />
              </el-button>
            </el-tooltip>
            <el-tooltip content="上传" placement="top" v-if="scope.row.status != 'draft' && scope.row.ossId === null">
              <el-button type="primary" circle link @click="handleFile(scope.row)">
                <svg-icon icon-class="UploadRounded" />
              </el-button>
            </el-tooltip>
            <el-tooltip content="下载" placement="top" v-if="scope.row.status != 'draft' && scope.row.ossId != null">
              <el-button type="primary" circle link @click="handleDownload(scope.row)">
                <svg-icon icon-class="SymbolsDownload" />
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除文件" placement="top" v-if="scope.row.status != 'draft' && scope.row.ossId != null">
              <el-button type="danger" circle link @click="handleDeleteFile(scope.row)">
                <svg-icon icon-class="DeleteOutline" />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 上传文件弹窗 -->
    <el-dialog v-model="dialogFile.visible" :title="dialogFile.title" style="width: 350px" append-to-body>
      <el-form ref="ossFormRef" label-width="80px">
        <el-form-item label="文件：">
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="1"
            :auto-upload="false"
            :show-file-list="true"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :on-change="handleFileChange"
          >
            <template #trigger>
              <el-button type="primary">请选择文件</el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="success" @click="submitUpload">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Apply" lang="ts">
import { delApply, deleteFile, getUser, listApply, uploadApplyFile } from '@/api/fill/apply';
import { ApplyQuery, ApplyVO } from '@/api/fill/apply/types';
import { getYear } from '@/hooks/useDate';
import { ref } from 'vue';
import { genFileId, UploadInstance, UploadProps, UploadRawFile } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { approval_status } = toRefs<any>(proxy?.useDict('approval_status'));

const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

/** 查询参数*/
const queryParams = ref<ApplyQuery>({
  pageNum: 1,
  pageSize: 10,
  year: getYear(),
  yardCode: undefined,
  yardName: undefined,
  deptCode: undefined,
  deptName: undefined,
  applyTheme: undefined,
  subjectCode: undefined,
  subjectName: undefined,
  type: 1
});
const columnLength = ref(140);
const applyList = ref<ApplyVO[]>([]);
/** 查询预算申请列表 */
const getList = async () => {
  loading.value = true;
  getUser()
    .then((res) => {
      let user = res.data;
      queryParams.value.deptCode = user.deptCode;
      queryParams.value.deptName = user.deptName;
      queryParams.value.yardCode = user.yardCode;
      queryParams.value.yardName = user.yardName;
    })
    .then(() => {
      listApply(queryParams.value)
        .then((res) => {
          applyList.value = res.data.records;
          total.value = res.data.total;
        })
        .then(() => {
          /*操作列表长度*/
          for (let item of applyList.value) {
            columnLength.value = 140;
            if (item.ossId != null) {
              columnLength.value = 190;
              break;
            }
          }
        });
    })
    .finally(() => (loading.value = false));
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  if (!queryParams.value.deptCode) {
    proxy?.$modal.msgError('暂无部门，不能进行申请！');
    return;
  }
  proxy.$tab.closePage(proxy.$route);
  // proxy.$router.push(`/fill/apply/applyFrom/index/add/add`);
  proxy.$router.push({
    path: `/fill/apply/applyFrom/index`,
    query: {
      type: 'add',
      year: queryParams.value.year,
      deptCode: queryParams.value.deptCode,
      deptName: queryParams.value.deptName,
      yardCode: queryParams.value.yardCode,
      yardName: queryParams.value.yardName
    }
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: ApplyVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/fill/apply/applyFrom/index`,
    query: {
      id: row.id,
      type: 'update'
    }
  });
};
/**
 * 查看详情
 * @param row
 */
const handleView = (row?: ApplyVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/fill/apply/applyFrom/index`,
    query: {
      id: row.id,
      type: 'view'
    }
  });
};

const ids = ref<Array<string | number>>([]);
/** 删除按钮操作 */
const handleDelete = async (row?: ApplyVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的数据项？').finally(() => (loading.value = false));
  await delApply(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'fill/apply/export',
    {
      ...queryParams.value
    },
    `预算申请.xlsx`
  );
};
/**----------------------------------文件-----------------------------------------------*/
// 打开文件连接
const handleViewFile = (row: ApplyVO) => {
  window.open(row.url, '_blank');
};
const buttonLoading = ref(false);
const dialogFile = reactive<DialogOption>({
  visible: false,
  title: ''
});
const ossFormRef = ref<ElFormInstance>();
//选中的行数据
const selectRow = ref<ApplyVO>();
/** 文件按钮操作 */
const handleFile = (row?: ApplyVO) => {
  fileList.value = [];
  selectRow.value = null;
  dialogFile.visible = true;
  dialogFile.title = '上传附件';
  selectRow.value = row;
};
/** 下载按钮操作 */
const handleDownload = (row: ApplyVO) => {
  proxy?.$download.oss(row.ossId);
};
const fileList = ref<any[]>([]);
const selectedFile = ref<any>();
const beforeUpload = (file: File) => {};
const handleFileChange = (file: any) => {
  // 存储选中的文件
  selectedFile.value = file;
};

const upload = ref<UploadInstance>();
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};
/**提交*/
const submitUpload = async () => {
  if (selectedFile.value) {
    const formData = new FormData();
    formData.append('file', selectedFile.value.raw);
    formData.append('id', selectRow.value.id.toString());
    await uploadApplyFile(formData).then((res) => {
      dialogFile.visible = false;
      ElMessage.success('上传成功');
      getList();
    });
  } else {
    ElMessage.error('请选择一个文件');
  }
};

/**上传取消*/
function cancel() {
  dialogFile.visible = false;
}

const handleDeleteFile = async (row?: ApplyVO) => {
  const ossId = row?.ossId;
  await proxy?.$modal.confirm('是否确认删除附件？');
  loading.value = true;
  await deleteFile(ossId).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};
/**------------------------------------------------------------------------------------*/

onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss"></style>
